<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>个人信息管理</p>
    </header>

    <!-- 用户信息编辑区域 -->
    <div class="profile-edit">
      <!-- 头像编辑部分 -->
      <div class="avatar-section">
        <div class="current-avatar">
          <img :src="user.userImg || defaultAvatar" @error="handleImageError" class="avatar-img">
          <p>当前头像</p>
        </div>
        
        <!-- 头像选择器 -->
        <div class="avatar-selector">
          <h3>选择预设头像</h3>
          <ul class="avatar-grid">
            <li v-for="(avatar, index) in presetAvatars" :key="index" @click="selectPresetAvatar(index)">
              <img :src="avatar" class="avatar-option">
            </li>
          </ul>
        </div>

        <!-- 上传自定义头像 -->
        <!-- <div class="avatar-upload">
          <h3>上传自定义头像</h3>
          <input 
            type="file" 
            id="avatarUpload" 
            accept="image/*" 
            @change="handleFileUpload"
            class="upload-input">
          <label for="avatarUpload" class="upload-btn">
            <i class="fa fa-cloud-upload"></i> 选择图片
          </label>
          <div v-if="uploadedImage" class="upload-preview">
            <img :src="uploadedImage" class="preview-img">
            <button @click="saveCustomAvatar" class="save-btn">保存为头像</button>
          </div>
        </div> -->
      </div>

      <!-- 基本信息编辑部分 -->
      <div class="info-section">
        <div class="form-group">
          <label for="username">用户名</label>
          <input 
            type="text" 
            id="username" 
            v-model="user.username" 
            placeholder="请输入用户名"
            maxlength="50">
        </div>

        <div class="form-group">
          <label>性别</label>
          <div class="gender-options">
            <label>
              <input 
                type="radio" 
                v-model="user.userSex" 
                :value="1"> 男
            </label>
            <label>
              <input 
                type="radio" 
                v-model="user.userSex" 
                :value="0"> 女
            </label>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button @click="saveProfile" :disabled="isSaving" class="save-profile-btn">
          <i v-if="isSaving" class="fa fa-spinner fa-spin"></i>
          {{ isSaving ? '保存中...' : '保存修改' }}
        </button>
        <button @click="cancelEdit" class="cancel-btn">取消</button>
      </div>
    </div>

    <Footer></Footer>
  </div>
</template>

<script>
import Footer from '../components/Footer.vue';

export default {
  name: 'ProfileEdit',
  components: {
    Footer
  },
  data() {
    return {
      user: {
        id: null,
        username: '',
        userSex: 0,
        userImg: ''
      },
      presetAvatars: [
        require('../assets/user1.png'),
        require('../assets/user2.png'),
        require('../assets/user3.png'),
        require('../assets/user4.png'),
        require('../assets/user5.png')
      ],
      defaultAvatar: require('../assets/default-avatar.png'),
      uploadedImage: null,
      isSaving: false,
      originalUser: {}
    }
  },
  created() {
    this.loadUserData();
  },
  methods: {
    // 加载用户数据
    loadUserData() {
      const sessionUser = this.$getSessionStorage('user');
      if (sessionUser) {
        this.user = {
          id: sessionUser.id || sessionUser.userId,
          username: sessionUser.username || sessionUser.userName,
          userSex: sessionUser.userSex || 0,
          userImg: sessionUser.userImg || ''
        };
        // 保存原始数据用于比较
        this.originalUser = {...this.user};
      } else {
        this.$router.push('/login');
      }
    },
    
    // 选择预设头像
    selectPresetAvatar(index) {
      this.user.userImg = this.presetAvatars[index];
    },
    
    // 处理文件上传
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      // 验证文件类型
      if (!file.type.match('image.*')) {
        alert('请选择图片文件');
        return;
      }
      
      // 验证文件大小 (限制2MB)
      if (file.size > 2 * 1024 * 1024) {
        alert('图片大小不能超过2MB');
        return;
      }
      
      // 转换为Base64
      const reader = new FileReader();
      reader.onload = (e) => {
        this.uploadedImage = e.target.result;
      };
      reader.readAsDataURL(file);
      
      // 重置文件输入，允许重复选择同一文件
      event.target.value = '';
    },
    
    // 保存自定义头像
    saveCustomAvatar() {
      if (!this.uploadedImage) {
        alert('请先上传图片');
        return;
      }
      
      this.user.userImg = this.uploadedImage;
      this.uploadedImage = null;
      alert('头像已设置为上传的图片');
    },
    
    // 保存个人信息
    async saveProfile() {
      if (this.isSaving) return;
      
      // 验证用户名
      if (!this.user.username || this.user.username.trim().length < 1) {
        alert('用户名不能为空');
        return;
      }
      
      // 检查是否有修改
      if (JSON.stringify(this.user) === JSON.stringify(this.originalUser)) {
        alert('没有修改任何信息');
        return;
      }
      
      this.isSaving = true;
      
      try {
        const response = await this.$axios.put(
          `/api/users/${this.user.id}`,
          {
            username: this.user.username,
            userSex: this.user.userSex,
            userImg: this.user.userImg
          },
          {
            headers: {
              'Content-Type': 'application/json'
            }
          }
        );
        
        if (response.data.success) {
          alert('个人信息更新成功');
          
          // 更新sessionStorage中的用户信息
          const updatedUser = {
            ...this.$getSessionStorage('user'),
            username: this.user.username,
            userSex: this.user.userSex,
            userImg: this.user.userImg
          };
          this.$setSessionStorage('user', updatedUser);
          
          // 更新原始数据
          this.originalUser = {...this.user};
        } else {
          throw new Error(response.data.message || '更新失败');
        }
      } catch (error) {
        console.error('保存失败:', error);
        alert('保存失败: ' + (error.response?.data?.message || error.message));
      } finally {
        this.isSaving = false;
      }
    },
    
    // 取消编辑
    cancelEdit() {
      if (JSON.stringify(this.user) !== JSON.stringify(this.originalUser)) {
        if (confirm('确定放弃修改吗？')) {
          this.user = {...this.originalUser};
          this.uploadedImage = null;
        }
      } else {
        this.$router.go(-1);
      }
    },
    
    // 处理图片加载错误
    handleImageError(e) {
      e.target.src = this.defaultAvatar;
    }
  }
}
</script>

<style scoped>
  /*************** 总容器 ***************/
  .wrapper {
    width: 100%;
    height: 100%;
    background-color: #f5f5f5;
    padding-bottom: 14vw;
  }

  /*************** header部分 ***************/
  header {
    width: 100%;
    height: 12vw;
    background-color: #0097FF;
    color: #fff;
    font-size: 4.8vw;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1000;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  /*************** 个人信息编辑区域 ***************/
  .profile-edit {
    width: 100%;
    margin-top: 12vw;
    padding: 4vw;
    box-sizing: border-box;
  }

  /*************** 头像编辑部分 ***************/
  .avatar-section {
    background-color: #fff;
    border-radius: 2vw;
    padding: 4vw;
    margin-bottom: 4vw;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }

  .current-avatar {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 6vw;
  }

  .avatar-img {
    width: 25vw;
    height: 25vw;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #eee;
    margin-bottom: 2vw;
  }

  .current-avatar p {
    font-size: 3.8vw;
    color: #666;
  }

  .avatar-selector h3,
  .avatar-upload h3 {
    font-size: 4vw;
    color: #333;
    margin-bottom: 3vw;
    padding-bottom: 2vw;
    border-bottom: 1px solid #eee;
  }

  .avatar-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 3vw;
    margin-bottom: 6vw;
  }

  .avatar-option {
    width: 100%;
    height: 20vw;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #eee;
    cursor: pointer;
    transition: all 0.3s;
  }

  .avatar-option:hover {
    transform: scale(1.05);
    border-color: #0097FF;
  }

  /*************** 上传自定义头像 ***************/
  .avatar-upload {
    margin-top: 4vw;
  }

  .upload-input {
    display: none;
  }

  .upload-btn {
    display: inline-block;
    padding: 2vw 4vw;
    background-color: #0097FF;
    color: #fff;
    border-radius: 4px;
    font-size: 3.8vw;
    cursor: pointer;
    margin-bottom: 4vw;
    transition: background-color 0.3s;
  }

  .upload-btn:hover {
    background-color: #0085e0;
  }

  .upload-btn i {
    margin-right: 2vw;
  }

  .upload-preview {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 4vw;
  }

  .preview-img {
    width: 25vw;
    height: 25vw;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #eee;
    margin-bottom: 3vw;
  }

  .save-btn {
    padding: 2vw 4vw;
    background-color: #38CA73;
    color: #fff;
    border: none;
    border-radius: 4px;
    font-size: 3.8vw;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .save-btn:hover {
    background-color: #2db863;
  }

  /*************** 基本信息编辑部分 ***************/
  .info-section {
    background-color: #fff;
    border-radius: 2vw;
    padding: 4vw;
    margin-bottom: 4vw;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }

  .form-group {
    margin-bottom: 6vw;
  }

  .form-group label {
    display: block;
    font-size: 4vw;
    color: #333;
    margin-bottom: 2vw;
  }

  .form-group input[type="text"] {
    width: 100%;
    padding: 3vw;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 4vw;
    box-sizing: border-box;
  }

  .gender-options {
    display: flex;
    gap: 6vw;
  }

  .gender-options label {
    display: flex;
    align-items: center;
    font-size: 4vw;
    color: #666;
  }

  .gender-options input[type="radio"] {
    margin-right: 2vw;
    width: 4vw;
    height: 4vw;
  }

  /*************** 操作按钮 ***************/
  .action-buttons {
    display: flex;
    gap: 4vw;
  }

  .save-profile-btn {
    flex: 1;
    height: 12vw;
    background-color: #0097FF;
    color: #fff;
    border: none;
    border-radius: 4px;
    font-size: 4.2vw;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
  }

  .save-profile-btn:hover:not(:disabled) {
    background-color: #0085e0;
  }

  .save-profile-btn:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }

  .cancel-btn {
    flex: 1;
    height: 12vw;
    background-color: #eee;
    color: #666;
    border: none;
    border-radius: 4px;
    font-size: 4.2vw;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
  }

  .cancel-btn:hover {
    background-color: #ddd;
  }

  /*************** 响应式设计 ***************/
  @media (min-width: 768px) {
    header {
      height: 60px;
      font-size: 20px;
    }
    
    .profile-edit {
      margin-top: 60px;
      max-width: 600px;
      margin-left: auto;
      margin-right: auto;
    }
    
    .avatar-img {
      width: 150px;
      height: 150px;
    }
    
    .avatar-grid {
      grid-template-columns: repeat(5, 1fr);
      gap: 15px;
    }
    
    .avatar-option {
      height: 100px;
    }
    
    .upload-btn {
      padding: 10px 20px;
      font-size: 16px;
    }
    
    .preview-img {
      width: 150px;
      height: 150px;
    }
    
    .save-btn {
      padding: 10px 20px;
      font-size: 16px;
    }
    
    .form-group label {
      font-size: 16px;
    }
    
    .form-group input[type="text"] {
      padding: 10px;
      font-size: 16px;
    }
    
    .gender-options {
      gap: 30px;
    }
    
    .gender-options label {
      font-size: 16px;
    }
    
    .gender-options input[type="radio"] {
      width: 16px;
      height: 16px;
    }
    
    .save-profile-btn,
    .cancel-btn {
      height: 50px;
      font-size: 18px;
    }
  }
</style>